use crate::i_result::IResult;
use crate::my_error::MyError;
use once_cell::sync::Lazy;

fn get_path() -> IResult<String> {
    let mut path = dirs::data_dir().ok_or(MyError::new_box("get home_dir error"))?;
    path.push("股票行情观察");
    path.push("数据库");
    Ok(path.to_str().unwrap_or_default().to_string())
}

static DB: Lazy<sled::Db> = Lazy::new(|| {
    let path = get_path().unwrap();
    let db = sled::open(path).unwrap();
    db
});

/// 查询
pub fn select(key: &str, tree_name: Option<String>) -> IResult<Option<String>> {
    return match tree_name {
        None => match DB.get(key)? {
            Some(v) => Ok(Some(String::from_utf8(v.to_vec()).unwrap_or_default())),
            None => Ok(None),
        },
        Some(tree_name) => {
            let tree1 = DB.open_tree(tree_name)?;
            match tree1.get(key)? {
                Some(v) => Ok(Some(String::from_utf8(v.to_vec()).unwrap_or_default())),
                None => Ok(None),
            }
        }
    };
}

/// 插入
pub fn insert(key: &str, value: &str, tree_name: Option<String>) -> IResult<()> {
    match tree_name {
        None => {
            DB.insert(key, value)?;
        }
        Some(tree_name) => {
            let tree1 = DB.open_tree(tree_name)?;
            tree1.insert(key, value)?;
        }
    };
    Ok(())
}

/// 删除数据数据
pub fn remove(key: &str, tree_name: Option<String>) -> IResult<()> {
    match tree_name {
        None => {
            DB.remove(key)?;
        }
        Some(tree_name) => {
            let tree1 = DB.open_tree(tree_name)?;
            tree1.remove(key)?;
        }
    };
    Ok(())
}
